package com.yh.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.SqlSession;

import com.yh.dao.OrderDao;
import com.yh.dao.UserDao;
import com.yh.db.SqlSessionFactoryUtil;
import com.yh.entity.OrderItem;
import com.yh.entity.PageBean;



/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method = request.getParameter("op");
		if("allOrder".equals(method)){
			allOrder(request,response);
		}
	}

	private void allOrder(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// TODO 自动生成的方法存根
		String pageCode = request.getParameter("pageCode");
		String entityId = request.getParameter("entityId");
		String userName = request.getParameter("userName");
	    Map<String,Object> map = new HashMap<String, Object>();
		PageBean<OrderItem> pb = new PageBean<OrderItem>();
		if(pageCode !=null && !"".equals(pageCode)){
			map.put("start", (Integer.parseInt(pageCode)-1)*pb.getPageSize());
			pb.setPageCode(Integer.parseInt(pageCode));	
		}else{
			map.put("start", 0);
			pb.setPageCode(1);
		}
		if(entityId !=null && !"".equals(entityId)){
			map.put("entityId",entityId);
		}
		if(userName !=null && !"".equals(userName)){
			map.put("userName", userName);
		}
		SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
		OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
		List<OrderItem> orderItems = orderDao.queryOrders(map);
		pb.setBeanList(orderItems);
		pb.setTotalCount(orderDao.countOrder(map));
		sqlSession.close();
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(JSONObject.fromObject(pb).toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
